package com.hyb.hybmodulesblog.controller.front;

import com.alibaba.fastjson.JSON;
import com.hyb.hybmodulesblog.domain.Article;
import com.hyb.hybmodulesblog.service.IArticleService;
import com.ruoyi.common.core.constant.ArticleConstant;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/front/article")
public class FrontArticleController {

    //热度统计
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    IArticleService articleService;


    @GetMapping("/getHot")
    public AjaxResult getHot(){


        Set<String> range = redisTemplate.opsForZSet().range(ArticleConstant.HOT_RANGE_KEY, ArticleConstant.INTEGERS[0], ArticleConstant.INTEGERS[1]);
        if (range==null) return AjaxResult.error("数据为空");

        LinkedList<Article> list=new LinkedList<>();

        for (String s : range) {
            Article article = articleService.selectArticleById(Long.parseLong(s));
            article.setArticleHot(redisTemplate.opsForZSet().score(ArticleConstant.HOT_RANGE_KEY,s).longValue());
            list.addFirst(article);
        }

        return AjaxResult.success().put("list",list);
    }

    @PostMapping("/setHot")
    public AjaxResult setHot(@RequestParam("articleId")String articleId){

        Article article = articleService.selectArticleById(Long.parseLong(articleId));

        if (article==null){
            return AjaxResult.error("该文章不存在");
        }
//        Long userId = SecurityUtils.getUserId();
//        LoginUser loginUser = SecurityUtils.getLoginUser();

//        redisTemplate.opsForSet().add(ArticleConstant.ARTICLE_KEY,articleId);
//        redisTemplate.opsForHash().put(ArticleConstant.HOT_KEY+articleId,userId+"", JSON.toJSONString(loginUser));
//

        redisTemplate.opsForZSet().incrementScore(ArticleConstant.HOT_RANGE_KEY,articleId,1.0);
        return AjaxResult.success();
    }
}
